#!/usr/bin/env python3

import zipfile
import tempfile
import os
import re

modules=[
        {
            "id": "ios-ringtones-current",
            "name": "iOS Ringtones (Current)",
            "version": "ios17",
            "description": "Current iOS ringtones (added in iOS 17)",
            "fileDir": "ringtones/current",
        },
        {
            "id": "ios-ringtones-26",
            "name": "iOS Ringtones (iOS 26)",
            "description": "iOS ringtones new in iOS 26",
            "fileDir": "ringtones/ios-26",
        },
        {
            "id": "ios-ringtones-classic",
            "name": "iOS Ringtones (Classic)",
            "description": "Classic iOS ringtones",
            "fileDir": "ringtones/classic",
        },
]

fields=['fileDir','targetDirs']
propFields=['id','name','description','version','versionCode','author']
defaults={
        "version": "ios26-b6",
        "author": "swiftycode",
        "versionCode": 1,
        "targetDirs": [
            "ringtones",
            ## Handled through customize.sh
            # "system/media/audio/ringtones",
            # "system/media/audio/alarms",
            # "system/product/media/audio/ringtones",
            # "system/product/media/audio/alarms",
        ],
        "customize_script": open("customize.sh").read()
}

tempdir=tempfile.TemporaryDirectory()
for item in modules:
    target_zip=f"{item.get('id', defaults.get('id'))}.zip"
    zf=zipfile.ZipFile(f"{tempdir.name}/{target_zip}", 'w')
    # Copy ringtone files
    counter=0
    source_dir=item.get('fileDir', defaults.get('fileDir'))
    for filename in os.listdir(source_dir):
        if re.fullmatch(r"[^.](?P<name>.+)\.m4a", filename)!=None:
            counter+=1
            for targetDir in item.get('targetDirs', defaults.get('targetDirs')):
                # Using zf.open instead of zf.write for same timestamp and checksum
                zf.open(f"{targetDir}/{filename}",'w').write(open(f"{source_dir}/{filename}",'rb').read())
    assert counter>0, f"No m4a audio files found in \"{source_dir}\""
    # Create module.prop
    moduleprop=""
    for field in propFields:
        moduleprop+=f"{field}={item.get(field, defaults.get(field))}\n"
    zf.open("module.prop",'w').write(bytes(moduleprop, 'utf-8'))
    # Create customize.sh
    customize_script=item.get('customize_script', defaults.get('customize_script'))
    zf.open("customize.sh",'w').write(bytes(customize_script, 'utf-8'))

    # Display info
    print(f"Created {target_zip}:")
    zf.printdir()
    print("module.prop:")
    print(moduleprop)

    # Move zip files to current directory
    zf.close()
    if os.path.exists(target_zip):
        assert not os.path.isdir(target_zip), f"A directory called \"{target_zip}\" already exists"
        os.remove(target_zip)
    os.rename(f"{tempdir.name}/{target_zip}", target_zip)

